package com.zygh.questionnairesurvey.server;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.questionnairesurvey.common.CommonResult;
import com.zygh.questionnairesurvey.entity.*;
import com.zygh.questionnairesurvey.entity.vo.*;
import com.zygh.questionnairesurvey.mapper.DeptMapper;
import com.zygh.questionnairesurvey.mapper.ProblemDetailsMapper;
import com.zygh.questionnairesurvey.mapper.QuestionnaireMapper;
import com.zygh.questionnairesurvey.mapper.UserInfoMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DateUtil.now;

@Service
public class UserService extends ServiceImpl<UserInfoMapper, UserInfo> {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private ProblemDetailsMapper problemDetailsMapper;
    @Resource
    private QuestionnaireMapper questionnaireMapper;
    @Resource
    private DeptMapper deptMapper;

    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    public CommonResult listAll(String name, Integer termStatus, Integer deptId, String warningsignal, Integer pageNum, Integer pageSize) {
        List<UserInfo> userInfos = userInfoMapper.findUserInfo(name, termStatus, deptId, warningsignal);
        if (StringUtils.isBlank(name) && StringUtils.isBlank(warningsignal) && deptId != null) {
            List<UserInfo> userPidInfo = userInfoMapper.findUserPidInfo(termStatus, deptId);
            userInfos.addAll(userPidInfo);
        }

        if (userInfos.size() > 0) {
            List<UserInfo> collect = userInfos.stream().skip(pageSize * (pageNum - 1)).limit(pageSize).collect(Collectors.toList());
            PageVo<UserInfo> PageVo = new PageVo<>();
            PageVo.setList(collect);
            PageVo.setPageNum(pageNum);
            PageVo.setPageSize(pageSize);
            PageVo.setTotal(userInfos.size());
            PageVo.setPages(userInfos.size() % pageSize == 0 ? userInfos.size() / pageSize : userInfos.size() / pageSize + 1);
            return new CommonResult().success(PageVo);
        }
        return new CommonResult().validateFailed("查询失败！");
    }


    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    public CommonResult getById(Integer id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (userInfo != null) {
            return new CommonResult().success(userInfo);
        }
        return new CommonResult().validateFailed("查询失败！");
    }

    /**
     * 新增，插入所有字段
     *
     * @param userInfo 新增的记录
     * @return 返回影响行数
     */
    public CommonResult insert(UserInfo userInfo) {
        userInfo.setCreatetime(DateUtil.parse(now()));
        UserInfo hasName = userInfoMapper.findUserByUsername(userInfo.getUserName());
        if (hasName != null) {
            return new CommonResult().validateFailed("该用户已存在！");
        }
        //默认密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        userInfo.setPassword(passwordEncoder.encode(userInfo.getUserName()));
        Boolean isSuperadmin = userInfo.getIsSuperadmin();
        if (isSuperadmin == null) {
            isSuperadmin = false;
        }
        if (isSuperadmin == false) {
            userInfo.setPassword(passwordEncoder.encode(userInfo.getUserName()));
        }
        if (isSuperadmin) {
            userInfo.setPassword(passwordEncoder.encode("888888"));
        }

        int insert = userInfoMapper.insert(userInfo);
        if (insert > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("新增失败！");
    }


    /**
     * 修改，修改所有字段
     *
     * @param userInfo 修改的记录
     * @return 返回影响行数
     */
    public CommonResult update(UserInfo userInfo) {
        if (StringUtils.isNotBlank(userInfo.getUserName()) && userInfo.getDeptId() != null) {
            Dept dept = deptMapper.selectById(userInfo.getDeptId());
            Questionnaire questionnaire = new Questionnaire();
            questionnaire.setDeptName(dept.getName())
                    .setDeptId(userInfo.getDeptId());
            questionnaireMapper.update(questionnaire, Wrappers.<Questionnaire>lambdaQuery()
                    .eq(Questionnaire::getWarningsignal, userInfo.getUserName()));
        }
        if (userInfo.getRoleId() == null) {
            userInfo.setRoleId(0);
        }
        if (StrUtil.isNotBlank(userInfo.getPassword())) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        }
        int insert = userInfoMapper.updateById(userInfo);
        if (insert > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("修改失败！");
    }

    public CommonResult updateBase(UserUpdateVO list) {
        int result = 0;
        String id = list.getId();
        String[] split = id.split(",");
        for (int i = 0; i < split.length; i++) {
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setId(Integer.valueOf(split[i])).setDeptId(list.getDeptId());
            result += userInfoMapper.updateById(userInfo1);
            UserInfo userInfo = userInfoMapper.selectById(split[i]);
            if (userInfo != null && list.getDeptId() != null) {
                Dept dept = deptMapper.selectById(list.getDeptId());
                Questionnaire questionnaire = new Questionnaire();
                questionnaire.setDeptName(dept.getName())
                        .setDeptId(list.getDeptId());
                questionnaireMapper.update(questionnaire, Wrappers.<Questionnaire>lambdaQuery()
                        .eq(Questionnaire::getWarningsignal, userInfo.getUserName()));
            }
        }
        return new CommonResult().success(result);

    }


    /**
     * 删除记录
     *
     * @param id 待删除的记录
     * @return 返回影响行数
     */
    public CommonResult delete(Integer id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (id == null) {
            return new CommonResult().validateFailed("查无此人！");
        }
        //删除问卷调查的个人信息
        questionnaireMapper.delete(Wrappers.<Questionnaire>lambdaQuery()
                .eq(Questionnaire::getWarningsignal, userInfo.getUserName()));
        //删除个人问题详情描述
        problemDetailsMapper.delete(Wrappers.<ProblemDetails>lambdaQuery()
                .eq(ProblemDetails::getWarningsignal, userInfo.getUserName()));
        int i = userInfoMapper.deleteById(id);
        if (i > 0) {
            return new CommonResult().success(userInfo);
        }
        return new CommonResult().validateFailed("删除失败！");
    }

    public UserVO getUserInfo(String username) {
        return userInfoMapper.getUserInfo(username);
    }

    /**
     * 查询没有填写调查问卷的警员
     *
     * @return CommonResult
     */
    public CommonResult findUserByQuest(Integer pageNum, Integer pageSize, Integer unitId,
                                        String code, String name) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfo> userByQuest = userInfoMapper.findUserByQuest(unitId, code, name);
        PageInfo<UserInfo> pageInfo = new PageInfo<>(userByQuest);
        return new CommonResult().success(pageInfo);
    }


    public CommonResult findUserInfoById(String deptId, String warningsignal, String name, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfoVO> userInfoById = userInfoMapper.findUserInfoById(deptId, warningsignal, name);
        userInfoById.stream().filter(Objects::nonNull).forEach(userInfoVO -> {
            List<Problem> countById = userInfoMapper.findCountById(deptId, userInfoVO.getUserName());
            userInfoVO.setCount(countById.size());
            Integer integer = problemDetailsMapper.selectCount(Wrappers.<ProblemDetails>lambdaQuery()
                    .eq(ProblemDetails::getWarningsignal, userInfoVO.getUserName()));
            userInfoVO.setCountDetail(integer);
        });
        PageInfo<UserInfoVO> pageInfo = new PageInfo<>(userInfoById);
        return new CommonResult().success(pageInfo);

    }

    /**
     * @param id 問題id
     * @return
     */
    public CommonResult findUserByProbelm(Integer id, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        List<UserInfoVO> userByProbelm = userInfoMapper.findUserByProbelm(id);
        map.put("count", userByProbelm.size());
        map.put("list", userByProbelm);
        mapList.add(map);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
        return new CommonResult().success(pageInfo);

    }

    public CommonResult findUserByNum(Integer unitId) {
        Map<String, Integer> map = new HashMap<>();
        //总人数
        Integer count = userInfoMapper.findUserCount(unitId);

        //已填写问卷调查的人数
        Integer num = userInfoMapper.findUserNum(unitId);
        map.put("sum", count);
        map.put("num", num);
        return new CommonResult().success(map);
    }


    public CommonResult updatePass(UserPasswordVo userPassword) {
        if (StrUtil.isEmpty(String.valueOf(userPassword.getId()))) {
            return new CommonResult().validateFailed("用户id不能为空！");
        }
        UserInfo userInfo = userInfoMapper.selectOne(Wrappers.<UserInfo>lambdaQuery()
                .eq(UserInfo::getId, userPassword.getId()));
        if (userInfo == null) {
            return new CommonResult().validateFailed("查无此人！");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(userPassword.getOldPwd(), userInfo.getPassword())) {
            return new CommonResult().validateFailed("原密码错误！");
        }
        userInfo.setPassword(passwordEncoder.encode(userPassword.getNewPwd()));
        userInfo.setPassStatus(1);
        userInfo.setCreatetime(DateUtil.parse(now()));
        userInfoMapper.updateById(userInfo);
        return new CommonResult().success();
    }

    /**
     * 根据用户名重置密码
     *
     * @param username 用户名（警号）
     * @return CommonResult
     */
    public CommonResult resetPasswords(String username) {
        if (StringUtils.isBlank(username)) {
            return new CommonResult().validateFailed("请填写警号！");
        }
        UserInfo userInfo = userInfoMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().
                eq(UserInfo::getUserName, username));
        if (userInfo == null) {
            return new CommonResult().validateFailed("查无此人！");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        UserInfo user = new UserInfo();
        user.setPassword(passwordEncoder.encode(username))
                .setCreatetime(DateUtil.parse(now()));
        int update = userInfoMapper.update(user, Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getUserName, username));
        if (update > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("重置失败！");
    }


    /**
     * 查询所有管理员
     *
     * @return
     */
    public CommonResult findUserAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfo> userInfos = userInfoMapper.selectList(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getIsSuperadmin, true));
        userInfos.forEach(userInfo -> {
            Dept dept = deptMapper.selectById(userInfo.getDeptId());
            userInfo.setDeptName(dept.getName());
        });
        PageInfo<UserInfo> pageInfo = new PageInfo<>(userInfos);
        return new CommonResult().success(pageInfo);
    }

    public CommonResult findUserCountByid(Integer id) {
        List<Integer> userCountByid = userInfoMapper.findUserCountByid(id);
        Integer[] stored = userCountByid.toArray(new Integer[userCountByid.size()]);
        Map<String, Object> map = new HashMap<>();
        map.put("policeNum", stored[0]);
        map.put("leadNum", stored[1]);
        map.put("workerNum", stored[2]);
        return new CommonResult().success(map);
    }


    /**
     * 根据问题id和部门id查询人员信息
     *
     * @param encoder 问题编号
     * @param deptId  部门id
     * @return CommonResult
     */
    public CommonResult findUserByProblem(Integer deptId, String encoder, Integer termStatus, String warningsignal,String name,
                                          Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProblemDetails> problemDetails = userInfoMapper.finUserByDetails(deptId, encoder, termStatus, warningsignal,name);
        problemDetails.forEach(detail -> {
            if (StringUtils.isNotBlank(detail.getPName())) {
                detail.setDeptName(detail.getPName() + "-" + detail.getDeptName());
            }
        });
        PageInfo<ProblemDetails> pageInfo = new PageInfo<>(problemDetails);
        return new CommonResult().success(pageInfo);

    }

}